//
//  WQKeyboardView.swift
//  1215-自定义键盘
//
//  Created by 王先强 on 15/12/15.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit

private let WQEmosionKeboardViewCellID = "WQEmosionKeboardViewCellID"


class WQKeyboardView: UIView {

    
    private var selectedEmotionCallBack: (emotion: WQEmotion) -> ()
    
    init(finishedCallBack: (selectedEmotion: WQEmotion) -> ()) {
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 225
        //纪录闭包属性
        selectedEmotionCallBack = finishedCallBack
        super.init(frame: rect)
        setupUI()
        
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.emotionKeyboardView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    @objc private func barBtnDidClicked(btn: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: btn.tag)
        self.emotionKeyboardView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    
    //懒加载工具条
    lazy var toolBottomBar: UIToolbar = UIToolbar()
    //懒加载表情视图
    lazy var emotionKeyboardView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: WQEmotionKeyboardLayout())
    //懒加载表情数组(大数组)
    lazy var emotionsPackages = WQEmotionsManager.sharedEmotionManager.emotionsPackages
    
    /// 私有类，只能在本类中使用
    private class WQEmotionKeyboardLayout: UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            super.prepareLayout()
            let columsCount:CGFloat = 7
            let rowCount: CGFloat = 3
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            let itemWH = UIScreen.mainScreen().bounds.width / columsCount
            itemSize = CGSizeMake(itemWH, itemWH)
            let margin = ((collectionView?.bounds.size.height)! - itemWH * rowCount) / 2.000001
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin
                , right: 0)
            collectionView!.bounces = false
            collectionView!.pagingEnabled = true
            collectionView!.showsHorizontalScrollIndicator = false
            collectionView!.backgroundColor = UIColor.lightGrayColor()
            collectionView!.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "emotionKeyboardViewCellID")

        }
        
    }
    
}

// MARK: - 准备子控件
extension WQKeyboardView {
    
    private func setupUI() {
        prepareEmotionKeboardView()
        prepareForToolBottomBar()
        addSubview(emotionKeyboardView)
        addSubview(toolBottomBar)
        
        emotionKeyboardView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(toolBottomBar.snp_top)
        }
        
        toolBottomBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        
    }
    ///  准备toolBottomBar
    private func prepareForToolBottomBar() {
        
        toolBottomBar.tintColor = UIColor.darkGrayColor()
        var index = 0
        var tempItems: [UIBarButtonItem] = [UIBarButtonItem]()
        for titleDict in emotionsPackages {
            let title = titleDict.group_name_cn
            tempItems.append((UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)))
            tempItems.append(UIBarButtonItem(title: title, style: .Plain, target: self, action: "barBtnDidClicked:"))
            tempItems.last!.tag = index++
            tempItems.append((UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)))
        }
        toolBottomBar.items = tempItems
        
    }
    ///  准备emosionKeboardView
    private func prepareEmotionKeboardView() {

        emotionKeyboardView.dataSource = self
        emotionKeyboardView.delegate = self
        emotionKeyboardView.registerClass(WQEmosionKeboardViewCell.classForCoder(), forCellWithReuseIdentifier: WQEmosionKeboardViewCellID)
        
        
    }
    
}
// emosionKeboardView的数据源方法实现
extension WQKeyboardView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        selectedEmotionCallBack(emotion: emotionsPackages[indexPath.section].emotions[indexPath.item])
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return emotionsPackages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emotionsPackages[section].emotions.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WQEmosionKeboardViewCellID, forIndexPath: indexPath) as! WQEmosionKeboardViewCell
        let emotion = WQEmotionsManager.sharedEmotionManager.emotionsPackages[indexPath.section].emotions[indexPath.item]
        cell.emotion = emotion
        
        return cell
    }
}


class WQEmosionKeboardViewCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emotionBtn)
//        emotionBtn.frame = UIEdgeInsetsInsetRect(contentView.bounds, UIEdgeInsetsMake(4, 4, 4, 4))
        emotionBtn.frame = CGRectInset(contentView.bounds, 6, 6)
        emotionBtn.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var emotion: WQEmotion? {
        didSet{
            emotionBtn.setImage(UIImage(contentsOfFile: emotion!.imagePath), forState: .Normal)
            emotionBtn.setTitle(emotion?.emoji ?? "", forState: .Normal)
            emotionBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
            
            if emotion!.isDelete {
                emotionBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    
    lazy var emotionBtn: UIButton = UIButton()
}



/// 底部工具条
class toolBar: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        recentEnmotionBtn = addbtnWith(title: "最近")
        defalutEnmotionBtn = addbtnWith(title: "默认")
        emojiEnmotionBtn = addbtnWith(title: "emoji")
        lxhEnmotionBtn = addbtnWith(title: "浪小花")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    var recentEnmotionBtn: UIButton?
    var defalutEnmotionBtn: UIButton?
    var emojiEnmotionBtn: UIButton?
    var lxhEnmotionBtn: UIButton?
    
    
    func addbtnWith(title title: String) -> UIButton {
        let btn = UIButton()
        
        btn .setTitle(title, forState: UIControlState.Normal)
        addSubview(btn)
        return btn
    }
}

















